package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 *
 * @author zhengsuyang
 * @date 2025-10-20
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ScriptEngine scriptEngine;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 触发警报
     */
    @Override
    public void alertFilter() {
        // 查询所有启动的规则
        LambdaQueryWrapper<AlertRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertRule::getStatus, 1);
        List<AlertRule> alertRuleList = this.list(queryWrapper);
        // 判断规则是否为空
        if (CollUtil.isEmpty(alertRuleList)) {
            return;
        }
        // 从redis中查找设备上报的数据
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        // 判断数据是否为空
        if (CollUtil.isEmpty(values)) {
            return;
        }
        List<DeviceData> dataList = new ArrayList<>();
        // 数据格式标准化处理 --- 把数据放到大集合里面
        for (Object value : values) {
            List<DeviceData> dataList1 = JSONUtil.toList(value.toString(), DeviceData.class);
            dataList.addAll(dataList1);
        }
        // 数据报警处理器
        for (DeviceData deviceData : dataList) {
            alterFilter(deviceData);
        }


    }

    /**
     * 数据报警处理器
     *
     * @param deviceData
     */
    private void alterFilter(DeviceData deviceData) {
        // 遍历报警规则两次
        // 针对一个设备的规则列表
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getStatus, 1);
        queryWrapper1.eq(AlertRule::getIotId, deviceData.getIotId());
        queryWrapper1.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getProductKey,deviceData.getProductKey());
        List<AlertRule> alertRule1 = this.list(queryWrapper1);
        // 针对所有设备的规则列表
        LambdaQueryWrapper<AlertRule> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AlertRule::getStatus, 1);
        queryWrapper2.eq(AlertRule::getIotId, "-1");
        queryWrapper2.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper2.eq(AlertRule::getProductKey,deviceData.getProductKey());
        List<AlertRule> alertRule2 = this.list(queryWrapper2);
        // 合并所有设备的规则列表
        Collection<AlertRule> alertRules = CollUtil.addAll(alertRule1, alertRule2);
        // 判断规则列表是否为空
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }
        // 遍历所有规则
        for (AlertRule alertRule : alertRules) {
            // 校验所有规则
            deviceDataAlarmHandler(alertRule, deviceData);
        }
    }

    /**
     * 校验所有规则
     *
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        // 开始处理第一层校验
        // 1.判断生效时间
        // 获取生效时间
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        // 获取上报时间
        LocalTime alterTime = deviceData.getAlarmTime().toLocalTime();
        // 判断上报时间是否在生效时间之内
        if (alterTime.isBefore(startTime) || alterTime.isAfter(endTime)) {
            return;
        }
        // 设备 + 产品 + 属性名 +规则名ID
        String alertCountKey=  CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+alertRule.getFunctionId()+alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId()+alertRule.getId();
        // 2.判断数据阈值
        String dataValue = deviceData.getDataValue();
        Double value = alertRule.getValue();
        String operator = alertRule.getOperator();
        // 拼接操作数
        String expresstion = dataValue + operator + value;
        // 判断上报数据是否达到阈值
        Boolean isReach=false;
        try {
            isReach = (Boolean) scriptEngine.eval(expresstion);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        // 未达到阈值
        if (!isReach){
            redisTemplate.delete(alertCountKey);
        }
        // 达到阈值
        // 判断沉默周期是否有
        if (redisTemplate.hasKey(slientKey)) {
            return;
        }
        // 没有沉默周期
        // 判断持续周期
        // 获取报警次数
        Long alterCount = redisTemplate.boundValueOps(alertCountKey).increment(1);
        // 获取持续周期
        Integer duration = alertRule.getDuration();
        if (duration>alterCount) {
            return;
        }
        // 校验全部通过触发报警
        // 删除redis报警数
        redisTemplate.delete(alertCountKey);
        // 添加沉默周期
        redisTemplate.boundValueOps(slientKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 插入报警数据
        insertAlertData(alertRule, deviceData);
    }

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    @Value("${alert.managerRole}")
    private String managerRole;
    /**
     * 插入报警数据
     * @param alertRule
     * @param deviceData
     */
    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
        // 判断是否是老人数据
        // 判断是否为固定设备
        List<Long> ids = new ArrayList<>();
        if (deviceData.getLocationType().equals(0)) {
            // 随身设备通知护理员
            ids = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        }
        // 固定设备
        else {
            if (deviceData.getPhysicalLocationType().equals(1)){
                // 不是老人的数据通知行政人员
                ids = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            }
            else if (deviceData.getPhysicalLocationType().equals(2)){
                ids = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        // 所有上报数据都要通知超级管理员
        List<Long> admins = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
        // 把id数据整合起来
        Collection<Long> idLists = CollUtil.addAll(ids, admins);
        // 把id数据去重
        ArrayList<Long> idList = CollUtil.distinct(idLists);
        List<AlertData> alertDataList = new ArrayList<>();
        for (Long id : idList) {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setAlertRuleId(alertRule.getId());
            alertData.setAlertReason(deviceData.getFunctionId() + alertRule.getOperator() + alertRule.getValue() + alertRule.getDuration() + alertRule.getAlertSilentPeriod());
//            alertData.setProcessingResult();
//            alertData.setProcessorId();
//            alertData.setProcessorName();
//            alertData.setProcessingTime();
            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(id);
            alertDataList.add(alertData);
        }
        // 批量新增
        alertDataService.saveBatch(alertDataList);
        // 通知异常人员弹窗
        websocketNotity(alertDataList.get(0), alertRule, idList);

    }

    /**
     * websocket推送消息
     * @param alertData
     * @param alertRule
     * @param idList
     */
    private void websocketNotity(AlertData alertData, AlertRule alertRule, ArrayList<Long> idList) {
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        System.out.println(alertNotifyVo.getAccessLocation());
        webSocketServer.sendMessageToConsumer(alertNotifyVo,idList);
    }


}
